/**
 * 比例尺网格组件
 * 用于在编辑模式下显示场景尺寸参考
 */

import * as THREE from 'three';

export class ScaleGrid {
    constructor() {
        // 配置
        this.visible = true;
        
        // 屏幕比例尺
        this.screenScaleElement = null;
        this.camera = null;
        this.cameraController = null;
        
        // 场景引用（用于获取包围盒）
        this.scene = null;
        
        // 默认参考距离
        this.defaultReferenceDistance = 10; // 默认10米
        this.maxScaleWidth = 200; // 最大宽度200px
        this.minScaleWidth = 60;  // 最小宽度60px
        
        this.initScreenScale();
    }
    
    /**
     * 初始化屏幕比例尺
     */
    initScreenScale() {
        this.screenScaleElement = document.getElementById('screen-scale-indicator');
        if (this.screenScaleElement) {
        }
    }
    
    /**
     * 设置相机引用（用于计算比例尺）
     */
    setCamera(camera, cameraController) {
        this.camera = camera;
        this.cameraController = cameraController;
        if (camera) {
            this.updateScreenScale();
        }
    }
    
    /**
     * 设置场景引用（用于获取包围盒）
     */
    setScene(scene) {
        this.scene = scene;
    }
    
    /**
     * 计算场景中所有可见物体的包围盒
     */
    getSceneBoundingBox() {
        if (!this.scene) return null;
        
        const box = new THREE.Box3();
        let hasObjects = false;
        
        this.scene.traverse((object) => {
            // 排除辅助对象、灯光、相机等
            if (object.isMesh && object.visible && 
                !object.userData?.isHelper && 
                !object.userData?.isScaleGrid &&
                !object.name?.includes('__')) {
                
                const objectBox = new THREE.Box3().setFromObject(object);
                if (objectBox.isEmpty() === false) {
                    box.union(objectBox);
                    hasObjects = true;
                }
            }
        });
        
        return hasObjects ? box : null;
    }
    
    /**
     * 更新屏幕比例尺显示
     */
    updateScreenScale() {
        if (!this.screenScaleElement || !this.camera) return;
        
        // 获取比例尺线条元素
        const scaleLine = this.screenScaleElement.querySelector('.scale-line');
        if (!scaleLine) return;
        
        // 计算相机到场景中心的距离（使用相机控制器的目标点）
        const cameraPosition = this.camera.position;
        
        // 获取相机控制器的target作为参考点
        let targetPoint = new THREE.Vector3(0, 0, 0);
        if (this.cameraController && this.cameraController.target) {
            targetPoint = this.cameraController.target.clone();
        }
        
        const distance = cameraPosition.distanceTo(targetPoint);
        
        // 根据相机距离和FOV计算屏幕比例尺
        const fov = this.camera.fov || 75;
        const aspect = window.innerWidth / window.innerHeight;
        
        // 计算视野宽度（以米为单位）
        const vFOV = fov * Math.PI / 180;
        const viewHeight = 2 * Math.tan(vFOV / 2) * distance;
        const viewWidth = viewHeight * aspect;
        const pixelToMeter = viewWidth / window.innerWidth;
        
        // 获取场景包围盒来确定合适的参考距离
        let referenceDistance = this.defaultReferenceDistance; // 默认10m
        const boundingBox = this.getSceneBoundingBox();
        
        if (boundingBox) {
            const size = new THREE.Vector3();
            boundingBox.getSize(size);
            // 使用包围盒最大边长的1/10作为参考，但限制在合理范围内
            const maxDimension = Math.max(size.x, size.y, size.z);
            if (maxDimension > 0) {
                // 选择合适的参考距离（包围盒的10%-30%之间）
                referenceDistance = Math.max(1, maxDimension * 0.15);
            }
        }
        
        // 将参考距离调整为整数刻度（1, 2, 5, 10, 20, 50, 100...）
        const magnitude = Math.pow(10, Math.floor(Math.log10(referenceDistance)));
        const normalized = referenceDistance / magnitude;
        
        let niceValue;
        if (normalized < 1.5) {
            niceValue = 1;
        } else if (normalized < 3.5) {
            niceValue = 2;
        } else if (normalized < 7.5) {
            niceValue = 5;
        } else {
            niceValue = 10;
        }
        
        const scaleDistance = niceValue * magnitude;
        
        // 计算对应的像素宽度
        let scaleWidth = scaleDistance / pixelToMeter;
        
        // 限制比例尺宽度在合理范围内
        scaleWidth = Math.max(this.minScaleWidth, Math.min(this.maxScaleWidth, scaleWidth));
        
        // 如果调整了宽度，重新计算实际距离
        const actualDistance = (scaleWidth * pixelToMeter);
        
        // 将实际距离调整为整数刻度
        const actualMagnitude = Math.pow(10, Math.floor(Math.log10(actualDistance)));
        const actualNormalized = actualDistance / actualMagnitude;
        
        let actualNiceValue;
        if (actualNormalized < 1.5) {
            actualNiceValue = 1;
        } else if (actualNormalized < 3.5) {
            actualNiceValue = 2;
        } else if (actualNormalized < 7.5) {
            actualNiceValue = 5;
        } else {
            actualNiceValue = 10;
        }
        
        const finalDistance = actualNiceValue * actualMagnitude;
        const finalWidth = finalDistance / pixelToMeter;
        
        // 智能选择合适的显示单位
        let displayValue, displayUnit;
        if (finalDistance < 0.01) {
            displayValue = Math.round(finalDistance * 10000) / 10;
            displayUnit = 'mm';
        } else if (finalDistance < 1) {
            displayValue = Math.round(finalDistance * 100);
            displayUnit = 'cm';
        } else if (finalDistance < 1000) {
            if (finalDistance < 10) {
                displayValue = Math.round(finalDistance * 10) / 10;
            } else {
                displayValue = Math.round(finalDistance);
            }
            displayUnit = 'm';
        } else {
            displayValue = Math.round(finalDistance / 100) / 10;
            displayUnit = 'km';
        }
        
        // 更新显示
        const label = this.screenScaleElement.querySelector('.scale-label');
        if (label) {
            label.textContent = `${displayValue}${displayUnit}`;
        }
        
        // 更新线条宽度
        scaleLine.style.width = `${Math.round(finalWidth)}px`;
    }
    
    
    /**
     * 显示比例尺（只显示屏幕UI）
     */
    show() {
        this.visible = true;
        
        // 显示屏幕比例尺UI
        if (this.screenScaleElement) {
            this.screenScaleElement.style.display = 'flex';
        }
    }
    
    /**
     * 隐藏比例尺（只隐藏屏幕UI）
     */
    hide() {
        this.visible = false;
        
        // 隐藏屏幕比例尺UI
        if (this.screenScaleElement) {
            this.screenScaleElement.style.display = 'none';
        }
    }
    
    /**
     * 切换显示/隐藏
     */
    toggle() {
        if (this.visible) {
            this.hide();
        } else {
            this.show();
        }
    }
    
    /**
     * 销毁比例尺，释放资源
     */
    dispose() {
    }
}

export default ScaleGrid;

